<template>
  <div class="business-store-edit">
    <el-button
      v-if="!$store.getters.banBtnList.includes('BTN_WCANYIN_GOODS_ATTRS_ADD')"
      size="small"
      type="primary"
      class="position-right"
      round
      @click="addMenu"
    >新建属性</el-button>
    <div class="list-table">
      <el-table :data="list" border style="width: 100%" empty-text="暂无数据">
        <el-table-column prop="name" label="属性名称" fixed />
        <el-table-column prop="values" label="选项">
          <template v-if="scope.row.values" slot-scope="scope">{{ scope.row.values.join(',') }}</template>
        </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template slot-scope="scope">
            <el-button
              v-if="!$store.getters.banBtnList.includes('BTN_WCANYIN_GOODS_ATTRS_EDIT')"
              type="text"
              size="mini"
              @click="menuEdit(scope.$index,scope.row)"
            >编辑</el-button>
            <el-button
              v-if="!$store.getters.banBtnList.includes('BTN_WCANYIN_GOODS_ATTRS_DELETE')"
              type="text"
              size="mini"
              @click="menuDetel(scope.$index,scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 新增/编辑菜品属性弹框 -->
    <el-dialog
      :visible.sync="dialogFormVisible"
      :title="titlestatus?'新建属性':'编辑属性'"
      width="600px"
      :close-on-click-modal="false"
      @close="close"
    >
      <el-form ref="form" :model="form" :rules="rules" class="form">
        <el-form-item :label-width="formLabelWidth" label="属性名称" prop="attributeName">
          <el-input v-model="form.attributeName" maxlength="30" />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="选项名称" class="is-required">
          <ul>
            <li v-for="(item,index) in form.optionNameList" :key="index" class="li-bo">
              <el-form-item
                style="display:inline-block"
                :prop="'optionNameList.' + index + '.list'"
                :rules="rules.attrValues"
              >
                <el-input v-model="item.list" maxlength="30" />
              </el-form-item>
              <el-button v-if="index!==0" type="text" size="mini" round @click="delAttrue(index)">删除</el-button>
            </li>
          </ul>
          <el-button
            :disabled="form.optionNameList.length>=5"
            type="text"
            size="mini"
            @click="addAttrue()"
          >新增选项</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" round @click="dialogFormVisible = false">取 消</el-button>
        <el-button size="small" round @click="confimAdd(titlestatus)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  searchAttributes,
  addAttributes,
  updateAttributes,
  deleteAttributes
} from '@/views/wcyModule/api/restaurant'
export default {
  props: ['shopId'],
  data() {
    return {
      /**
         * 表单校验字段相关
         */
      rules: {
        attributeName: [
          {
            required: true,
            message: '请输入属性名称',
            trigger: ['change']
          }
        ],
        attrValues: [
          {
            required: true,
            message: '请输入选项值',
            trigger: ['change']
          }
        ]
      },
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      itemNum: 1,
      titlestatus: 1,
      list: [],
      dialogFormVisible: false,
      form: {
        id: '',
        attributeName: '',
        optionNameList: [{ list: '' }]
      },
      formLabelWidth: '120px'
    }
  },
  watch: {
    shopId(val) {
      this.initData()
    }
  },
  mounted() {
    this.paginationConfig.total = 1
    this.initData()
  },
  beforeDestroy() {
    sessionStorage.setItem('attribute', JSON.stringify(this.list))
  },
  methods: {
    initData() {
      searchAttributes(this.shopId).then(res => {
        if (res.code === 0) {
          this.list = res.data
        }
      })
    },
    pageChange() {},
    sizesChange() {},
    delAttrue(index) {
      this.form.optionNameList.splice(index, 1)
    },
    menuEdit(index, row) {
      this.titlestatus = 0
      this.dialogFormVisible = true
      this.form.id = row.id
      this.form.attributeName = row.name
      const params = row.values
      // params = params.split('，');
      this.form.optionNameList = []
      for (let i = 0; i < params.length; i++) {
        this.form.optionNameList.push({ list: params[i] })
      }
    },
    addMenu() {
      this.form = {
        id: '',
        attributeName: '',
        optionNameList: [{ list: '' }]
      }
      this.titlestatus = 1
      this.dialogFormVisible = true
    },
    addAttrue() {
      if (this.form.optionNameList.length <= 4) {
        this.form.optionNameList.push({ list: '' })
      }
    },
    close() {
      this.$refs.form.resetFields()
    },
    confimAdd(titlestatus) {
      this.$refs.form.validate(valid => {
        if (valid) {
          const values = []
          const list = JSON.parse(JSON.stringify(this.form.optionNameList))
          list.forEach(v => {
            values.push(v.list)
          })
          const data = {
            shopId: this.shopId,
            name: this.form.attributeName,
            values: values
          }
          if (titlestatus === 1) {
            addAttributes(data).then(res => {
              if (res.code === 0) {
                this.dialogFormVisible = false
                this.$notify({
                  title: '成功',
                  message: '添加成功',
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
                this.initData()
              }
            })
          } else {
            data.id = this.form.id
            updateAttributes(data).then(res => {
              if (res.code === 0) {
                this.dialogFormVisible = false
                this.$notify({
                  title: '成功',
                  message: '修改成功',
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
                this.initData()
              }
            })
          }
        }
      })
    },
    menuDetel(index, row) {
      this.$confirm(`此操作将永久删除属性${row.name}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        roundButton: true
      })
        .then(() => {
          const data = {
            id: row.id,
            shopId: row.shopId
          }
          deleteAttributes(data).then(res => {
            if (res.code === 0) {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
              this.initData()
            }
          })
        })
        .catch(() => {})
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .business-store-edit {
    form .el-input {
      width: 300px;
    }
    .app-uploader-img-plus {
      width: 180px;
      height: 180px;
      .app-uploader-img-plus-icon {
        font-size: 36px;
        color: #8c939d;
        width: 180px;
        height: 180px;
        line-height: 180px;
        text-align: center;
      }
      .avatar {
        width: 180px;
        height: 180px;
        display: block;
      }
    }
    .upload_tips {
      margin: 20px 0 0 20px;
      li {
        margin-top: 10px;
        font-size: 14px;
        line-height: 16px;
        color: $dark-font-color;
      }
    }
  }
  .position-right {
    float: right;
    margin-bottom: 10px;
  }

  .mg-bo {
    margin-bottom: 30px;
    max-width: 330px !important;
  }
  .li-bo {
    margin-bottom: 20px;
  }
</style>
